import re, os
import paramiko
from paramiko  import SSHClient
class PerfSSH(SSHClient):
    def __init__(self):
        SSHClient.__init__(self)
        self.sftp = None
    def recusive_put(self, localpath, remotepath):
        dirs = os.listdir(localpath) 
        try:
            self.sftp.mkdir(remotepath)
        except IOError:
            pass
        for dir in dirs:
            print dir
            if os.path.isdir(localpath + '/' + dir):
                try:
                    self.sftp.mkdir(remotepath + '/' + dir)
                except IOError:
                    pass
                finally:
                    self.recusive_put(os.path.join(localpath, dir), os.path.join(remotepath, dir))
            else:
                self.sftp.put(localpath + '/' + dir, remotepath + '/' + dir)
    def chdir(self, dir):
        self.sftp.chdir(dir)

    def put(self, localpath, remotepath):
        self.sftp.put(localpath, remotepath)
    def remove(self, path):
        self.sftp.remove(path)
    
    def connect(self, opts):
    
        self.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
        SSHClient.connect(self, opts['server'], opts['port'], username=opts['username'], password=opts['password'], timeout=opts['timeout']) 

        self.sftp = self.open_sftp()
    
    def exec_command(self, cmd):
        stdin, stdout, stderr = SSHClient.exec_command(self, cmd) 
        for std in stdout.readlines(): 
            print std, 
    
    def close(self):
        self.sftp.close()
        SSHClient.close(self) 

if __name__ == '__main__':
    login = {'server':'202.173.9.17', 'port':22, 'username':'root', 'password':'zdns@knet.cn', 'timeout':3}
    localpath=os.getcwd()
    remotepath="/root/just_test"
    sshclient = PerfSSH() 
    sshclient.connect(login)
    sshclient.exec_command('ls -l')
    #sshclient.recusive_put(localpath, remotepath)
    sshclient.put(localpath + '/bind.tar.gz', remotepath + '/bind.tar.gz')
    sshclient.close()
